<div class="modal fade" id="lecture_modal" role="dialog">
    <div class="modal-dialog" style="width:50%;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h2 class="modal-title" id="myModalLabel">New Lecture</h2>
            </div>
            <div class="modal-body">
                {% include "teacher/lecture/form.html" with form=form %}
                
                <!-- Error Message Box -->
                <div id="error_box" name="error_box" class="alert alert-danger alert-dismissable" hidden="true">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                    ERROR: This is to be filled in by the "print_error" function. If you see this message that means there's an error with your javascript somewhere.
                </div><!-- /.Error Message Box -->
            </div>
            <div class="modal-footer">
                <button onclick="ajax_create_lecture();"
                             id="submit_lecture_btn"
                           name="submit_lecture_btn"
                           type="button"
                          class="btn btn-primary">
                    <i class="fa fa-check-circle"></i> Submit
                </button>
            </div>
        </div>
    </div>
</div>
<script>
    /**
     * Dynamic UI Code.
     *  To give our application a dynamic feel, the following jQuery code will be
     *  used to perform various UI changes.
     */
     $(document).ready(function(){
        $('#lecture_modal').on('hidden.bs.modal', function (e) {
            $('#lecture_modal').html('');
            $('#add_lecture_btn').prop("disabled", false);
            $('#edit_{{ form.instance.lecture_id }}_btn').prop("disabled", false);
                               
        });
    });
    
    /**
     * Function looks at the youtube url and either returns the URL or if
     * it detects a user added a iframe image, it then parses out the stuff
     * and returns only the URL. Also if URL is simply copied from browser URL
     * then parse out the YouTube ID and return embedded link.
     */
    function get_youtube_url()
    {
        // If someone enters something like: <iframe .... blah blah ... </iframe>
        var youtube_url = $('#id_youtube_url').val();
        if (youtube_url.indexOf("<iframe") > -1)
        {
            // Split it up by whitespace and find 'src='
            var split = youtube_url.split(' ');
            for(var i in split)
            {
                if (split[i].indexOf("src=") > -1)
                {
                    var code = split[i];
                    var url_with_doublequotes = code.split('=')[1];
                    var url = str = url_with_doublequotes.replace(/"/g, "");
                    youtube_url = url;
                    break;
                }
            }
        }
                                                                  
        // If someone entered a URL like this: https://www.youtube.com/watch?v=_Leog98q6iA
        if (youtube_url.indexOf("?v=") > -1)
        {
            youtube_id = youtube_url.split('?v=')[1];
            youtube_url = "https://www.youtube.com/embed/" + youtube_id;
        }
         
        // If someone shares a URL like this: https://youtu.be/_Leog98q6iA
        if (youtube_url.indexOf("https://youtu.be") > -1)
        {
            youtube_id = youtube_url.split('https://youtu.be/')[1];
            youtube_url = "https://www.youtube.com/embed/" + youtube_id;
        }
                
        return youtube_url;
    }
    
    /**
     *  Function will call AJAX function to load the register.
     */
    function ajax_create_lecture()
    {
        $('#submit_lecture_btn').prop("disabled", true); // Lock button
        
        // create a FormData Object using your form dom element
        var data = new FormData();
        data.append('csrfmiddlewaretoken', '{{ csrf_token }}');
        data.append('lecture_id', $('#id_lecture_id').val());
        data.append('title', $('#id_title').val());
        data.append('description', $('#id_description').val());
        data.append('lecture_num', $('#id_lecture_num').val());
        data.append('week_num', $('#id_week_num').val());
        data.append('youtube_url', get_youtube_url());
        data.append('vimeo_url', $('#id_vimeo_url').val());
        data.append('preferred_service', $('#id_preferred_service').val());
        jQuery.ajax({
            url: 'save_lecture',
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            success: function(json_result){
                // success code execution here
                $('#submit_lecture_btn').prop("disabled", false); // Unlock button
                if (json_result.status == "success")
                {
                    $('#lecture_modal').modal('hide');
                    ajax_refresh_lectures_table();
                }
                else
                {
                    print_error(json_result.message);
                }
            },
            error: function(xhr,status,error) {
                // error code here
            },
            complete: function(xhr,status) {
               // completion code here
            }
        });

    }

    /**
     * Prints a error box with the contents of the errors received from the server.
     */
    function print_error(json_result)
    {
        $('#error_box').prop("hidden", false); // Display error box.
    
        // Iterate through the JSON array of arrays and generate an error string.
        var message = "<b>Error(s):</b><hr/>";
        var data = $.parseJSON(json_result)
        for (var key in data) {
            if (data.hasOwnProperty(key)) { // this will check if key is owned by data object and not by any of it's ancestors
                message += "<p>" + key + ": " + data[key] + "<p>";
            }
        }
    
        // Replace the error string with the contents of the error box.
        $('#error_box').html(message);
    }
</script>
